<template>
	<view class="poster_page">
		<swiper :style="{height:fullHeight}" class="swiper-tall" :indicator-dots="indicatorDots" :autoplay="autoplay"
			:previous-margin="previousMargin" :next-margin="nextMargin" :circular="circular" @change="change"
			:current="swiperIndex">
			<swiper-item class="swiper-container" v-for="(item, index) of promoteBgImgs" :key="index"
				:item-id="String(index)" :data-year="index">
				<view class="swiper-item" :animation="animationData[index]" :class="{ active: swiperIndex == index }">
					<view class="swiper-mask"></view>
					<image class="poster-bg-image" :src="imgSrc+item.backgroundPic"></image>
					<image class="tui-avatar poster-avatar" :src="memberInfo.headimgurl" mode="头像"
						:style="{width:item.headw,height:item.headh,left:item.headx,top:item.heady}"></image>
					<!-- <view class="poster-username" :style="{top:item.userNamey}">
						<text class="name">{{memberInfo.userName}}</text>
						<text class="num" v-if="memberInfo.agencyId"></text>({{memberInfo.agencyId}})
					</view> -->
					<image class="poster-code-image" :src="promoteCodeImg" mode="aspectFit"
						:style="{width:item.codew,height:item.codeh,left:item.codex,top:item.codey}"></image>
					
					<!-- 生成海报 -->
					<button class="poster-btn" :class="btnDisabled?'disabled-btn':''" @click="shareFc"
						:style="{width:item.shareBtnw,height:item.shareBtnh,lineHeight:item.shareBtnh,'border-radius':item.shareBtnr,left:item.shareBtnx,top:item.shareBtny}"
						:disabled="btnDisabled">点我分享给朋友</button>

				</view>
			</swiper-item>
		</swiper>

		<!-- 图片展示由自己实现 -->
		<QSPopup ref="popup">
			<view class="flex-column">
				<view class="popup-close iconfont iconguanbi4" @tap='hideFc'></view>
				<view class="img">
					<image :src="posterImage || ''" mode="widthFix" class="posterImage"></image>
				</view>

				<view class="flex-row" :class="posterBtnDisabled?'disabled-style':''">
					<!-- #ifndef H5 -->
					<view class="btn" @tap.prevent.stop="onSaveImg">
						<image src="~@/packageB/static/img/pic.png"></image>
						<view class="text">保存图片</view>
					</view>
					<!-- #endif -->
					<!-- #ifdef H5 -->
					<view class="btn" @tap.prevent.stop="onSaveImg">
						<view class="text">长按保存图片</view>
					</view>
					<!-- #endif -->
					<!-- #ifdef APP-PLUS -->
					<view class="btn" @tap.prevent.stop="onAppShare('1')">
						<view class="icon-wrap">
							<i class="iconfont iconweixin green"></i>
							<view class="bg"></view>
						</view>
						<view class="text">分享好友</view>
					</view>
					<view class="btn" @tap.prevent.stop="onAppShare('2')">
						<view class="icon-wrap">
							<i class="iconfont iconpengyouquan yellow"></i>
							<view class="bg"></view>
						</view>
						<view class="text">朋友圈</view>
					</view>
					<!-- #endif -->
				</view>
			</view>
		</QSPopup>

		<canvas class="poster_canvas" id="default_PosterCanvasId" canvas-id="default_PosterCanvasId"
			:style="{width: (poster.width||10) + 'px', height: (poster.height||10) + 'px'}"></canvas>

		<tki-qrcode ref="qrcode" :val="qrVal" :size=382 :unit="unit" :onval="true" :loadMake="loadMake"
			:usingComponents="true" @result="qrR" :show="false" :showLoading="true" />
		<loading></loading>
		<tui-modal></tui-modal>
	</view>
</template>

<script>
	import tuiButton from "@/components/button/button"
	import tkiQrcode from '@/components/tki-qrcode/tki-qrcode.vue';

	import QSPopup from "@/packageB/components/QS-popup/QS-popup.vue"
	import _app from '@/packageB/static/QS-SharePoster/app.js';
	import {
		getSharePoster
	} from '@/packageB/static/QS-SharePoster/QS-SharePoster.js';

	let settingWritePhotosAlbum = false;
	export default {
		components: {
			tuiButton,
			tkiQrcode,
			QSPopup
		},
		data() {
			return {
				imgSrc: this.$store.state.imgUrl,
				promoteBgImgs: [],
				promoteOldInfo: [],
				promoteCodeImg: "",
				shareInfo: {
					shareContent: "Dr商城",
					shareImg: "",
					shareTitle: "Dr商城",
				},
				h5SaveImg: "",
				qrVal: null,
				unit: 'upx',
				loadMake: true,
				screenHeight: 0,
				animationData: {
					// 0:{},
					// 1:{},
				},
				title: '0',
				indicatorDots: false,
				autoplay: false,
				previousMargin: '0px',
				nextMargin: '0px',
				// nextMargin: uni.upx2px(10) + 'px',
				circular: true,
				zoomParam: 1.0,
				swiperIndex: 0,
				data: [],
				max: 0,
				memberInfo: {
					headimgurl: '../../../static/img/mine_def_touxiang_3x.png',
					nickName: '微信昵称',
					userName: '姓名',
					agencyId: '6位码'
				}, //会员信息

				poster: {},
				posterImage: '', //生成的海报路径
				canvasId: 'default_PosterCanvasId',
				btnDisabled: false,
				//服务器地址
				serverUrl: "so-fast-fs/fs/common/aliyunfile/upload",
				serverUrlDown: "so-fast-fs/fs/common/aliyunfile/download",
				bucketType: 'tmp',
				curHeight: 0,
				posterBtnDisabled:false,//生成海报后，禁止多次点击操作按钮
			};
		},
		//第一次加载
		onLoad(options) {
			this.animation = uni.createAnimation();
			this.animation.scale(this.zoomParam).step();
			this.animationData[0] = this.animation.export();

			this.getPoster();
			if (!this.$util.checkTokenAndInviterId(options)) {
				// 检查token和邀请人信息，无token退出方法
				return;
			}
			const res = uni.getSystemInfoSync();
			this.curHeight = res.windowHeight;
		},
		computed: {
			fullHeight() {
				const res = uni.getSystemInfoSync();
				return res.windowHeight + 'px';
				// return (667 * res.windowWidth) / 375 + 'px';
			}
		},
		//方法
		methods: {
			hideFc() {
				this.$refs.popup.hide()
				uni.hideLoading();
				this.posterBtnDisabled=false
			},
			async shareFc() { //生成海报
				let that = this;
				this.btnDisabled = true;
				let item = this.promoteOldInfo[this.swiperIndex];
				let bgUrl = item.backgroundPic;
				// #ifdef H5
				bgUrl=this.$util.serviceUrl() +'/prod-api/'+ that.serverUrlDown+'?path='+decodeURIComponent(item.backgroundPic)
				// #endif
				try {
					const d = await getSharePoster({
						_this: this, //若在组件中使用 必传
						type: 'testShareType',
						posterCanvasId: this.canvasId, //canvasId
						backgroundImage: bgUrl,
						// backgroundImage: '../../static/img/poster.png',
						delayTimeScale: 20, //延时系数
						canvas2image: false, //是否调用uni.canvasToTempFilePath 生成图片, 若不为false则判定为true
						drawArray: ({
							bgObj,
							type,
							bgScale
						}) => {
							const fontSize = bgObj.width * 0.045;
							const lineHeight = bgObj.height * 0.04;
							let codex = bgObj.width * item.codex / 375;
							let headx = bgObj.width * item.headx / 375;
							
							let heady = bgObj.height * item.heady / 725;
							let codey = bgObj.height * item.codey / 725;
							let codew = bgObj.width * 150 / 375;
							let headw = bgObj.width * 90 / 375;
							//可直接return数组，也可以return一个promise对象, 但最终resolve一个数组, 这样就可以方便实现后台可控绘制海报
							return new Promise((rs, rj) => {
								rs([{
										type: 'custom',
										setDraw(Context) {
											Context.setFillStyle('black');
											Context.setGlobalAlpha(0.3);
											Context.fillRect(0, bgObj.height, bgObj.width,
												bgObj
												.height * 0.2);
											Context.setGlobalAlpha(1);
										}
									},
									{
										type: 'image',
										url: that.promoteCodeImg, //二维码
										alpha: 1,
										dx: codex,
										dy: codey,
										dWidth: codew,
										dHeight: codew,
									},
									{
										type: 'image',
										url: that.memberInfo.headimgurl, //头像
										alpha: 1,
										 dx: headx,
										dy: heady,
										infoCallBack(imageInfo) {
											let scale = bgObj.width * 0.2 / imageInfo
												.height;
											return {
												circleSet: {
													x: imageInfo.width * scale / 2,
													y: bgObj.width * 0.2 / 2,
													r: bgObj.width * 0.2 / 2
												}, // 圆形图片 , 若circleSet与roundRectSet一同设置 优先circleSet设置
												dWidth: imageInfo.width *
													scale, // 因为设置了圆形图片 所以要乘以2
												dHeight: bgObj.width * 0.2,
												/* roundRectSet: { // 圆角矩形
													r: imageInfo.width * .1
												} */
											}
										}
									},
									// {
									// 	type: 'text',
									// 	fontStyle: 'normal',
									// 	text: that.memberInfo.userName+'(' + that.memberInfo.agencyId + ')',
									// 	size: fontSize,
									// 	serialNum: 0,
									// 	id: 'lineFeed',
									// 	// dx: 0,
									// 	dy: userNamey,
									// 	textAlign: 'left',
									// 	infoCallBack(textLength) {
									// 		return {
									// 			dx: (bgObj.width - textLength)/2,
									// 		}
									// 	},
									// },
								]);
							})
						},
						setCanvasWH: ({
							bgObj,
							type,
							bgScale
						}) => { // 为动态设置画布宽高的方法，
							this.poster = bgObj;
						}
					});
					_app.showLoading('正在输出图片');
					uni.canvasToTempFilePath({
						canvasId: this.canvasId,
						success: res => {
							_app.hideLoading();
							this.posterImage = res.tempFilePath; //海报图片
							this.promoteBgImgs[this.swiperIndex].temporary = this.posterImage;
							this.$refs.popup.show()
							this.btnDisabled = false;
						},
						fail: err => {
							this.btnDisabled = false;
							console.log('生成异常', err)
						}
					})
				} catch (e) {
					_app.hideLoading();
					_app.showToast(JSON.stringify(e));
					console.log(JSON.stringify(e));
				}
			},

			qrCodeInit() {
				this.$http.qrCodeInit().then((res) => {
					if (res.status === 0) {
						this.memberInfo = res.data;
						this.qrVal = res.data.storeBaseUrl;

					}
				})
			},
			getPoster() {
				let params = {
					current: 1,
					pageSize: 100,
				}
				this.$http.getPoster().then((res) => {
					if (res.status === 0) {
						this.qrCodeInit();
						this.promoteBgImgs = res.data.records;
						console.log(this.promoteBgImgs)

						let len = this.promoteBgImgs.length;
						for (let i = 0; i < len; i++) {
							this.animationData[i] = {};
							this.promoteBgImgs[i].temporary = '';
						}

						this.promoteOldInfo = JSON.parse(JSON.stringify(res.data.records));
						res.data.records.forEach(item => {
							item.codew = this.calculateX(150);
							item.codeh = this.calculateX(150);
							item.shareBtnw = this.calculateX(270);
							item.shareBtnh = this.calculateX(50);
							item.shareBtnr = this.calculateX(25);
							item.headw = this.calculateX(70);
							item.headh = this.calculateX(70);
							
							item.codex = this.calculateX(item.codex);
							item.headx = this.calculateX(item.headx);
							item.shareBtnx = this.calculateX(item.shareBtnx);
							item.sixNumx = this.calculateX(item.sixNumx);
							item.userNamex = this.calculateX(item.userNamex);
							
							item.topText = this.calculateY((item.heady-50), 'y');//
							item.userNamey = this.calculateY((item.heady+70), 'y');//写在item.heady之上
							item.midText = this.calculateY((item.heady+98), 'y');//
							item.heady = this.calculateY(item.heady, 'y');
							item.sixNumy = this.calculateY(item.sixNumy, 'y');
							// item.userNamey = this.calculateY(item.userNamey, 'y');
							
							
							item.codey = this.calculateY(item.codey, 'y');
							item.shareBtny = this.calculateY(item.shareBtny, 'y');
							

							
						})

					}
				})
			},

			change(e) {
				this.swiperIndex = e.detail.current;
				// this.title = e.detail.currentItemId;
				for (let key in this.animationData) {
					if (e.detail.currentItemId == key) {
						// this.animation.scale(this.zoomParam).step();
						this.animationData[key] = this.animation.export();
					} else {
						// this.animation.scale(0.98, 0.9).step();
						this.animationData[key] = this.animation.export();
					}
				}
			},
			qrR(path) {
				let that = this;
				this.promoteCodeImg = path;
			},
			// 轮播图变化
			onSwiperChange(e) {
				this.swiperIndex = e.detail.current;
			},
			handleShowPoster() {
				// this.canvasFlag = false
				this.$refs.hchPoster.posterShow()
			},
			// 保存图片
			async onSaveImg() {
				let that=this;
				if(this.posterBtnDisabled){
					return;
				}
				this.posterBtnDisabled=true;
				let imgUrl = "";
				if (this.promoteBgImgs[this.swiperIndex] && this.promoteBgImgs[this.swiperIndex].temporary) {
					imgUrl = await this.promoteBgImgs[this.swiperIndex].temporary;
				} else {
					imgUrl = await this.posterImage;
				}
				
				// #ifdef H5
				this.h5SaveImg = imgUrl;
				uni.hideLoading();
				this.posterBtnDisabled=false;
				// #endif
				
				// #ifdef MP-WEIXIN
				uni.showLoading({
					title: '海报下载中'
				});
				if (settingWritePhotosAlbum) {
					uni.getSetting({
						success: res => {
							if (res.authSetting['scope.writePhotosAlbum']) {
								uni.saveImageToPhotosAlbum({
									filePath: imgUrl,
									success: () => {
										uni.hideLoading();
										that.posterBtnDisabled=false;
										uni.showToast({
											title: '保存成功'
										});
									},fail: () => {
										that.posterBtnDisabled=false;
										uni.hideLoading();
										that.$util.toast('保存失败');
									}
								});
							} else {
								uni.showModal({
									title: '提示',
									content: '请先在设置页面打开“保存相册”使用权限',
									confirmText: '去设置',
									cancelText: '算了',
									success: data => {
										if (data.confirm) {
											uni.openSetting();
										}
									}
								});
								that.posterBtnDisabled=false;
								uni.hideLoading();
							}
						},fail: () => {
							that.posterBtnDisabled=false;
							uni.hideLoading();
							that.$util.toast('保存失败');
						}
					});
				} else {
					settingWritePhotosAlbum = true;
					uni.authorize({
						scope: 'scope.writePhotosAlbum',
						success: () => {
							uni.saveImageToPhotosAlbum({
								filePath: imgUrl,
								success: () => {
									that.posterBtnDisabled=false;
									uni.hideLoading();
									uni.showToast({
										title: '保存成功'
									});
								}
							});
						},fail: () => {
							that.posterBtnDisabled=false;
							uni.hideLoading();
							that.$util.toast('保存失败');
						}
					});
				}
				// #endif
				
				// #ifdef APP-PLUS
				uni.showLoading({
					title: '海报下载中'
				});
				uni.saveImageToPhotosAlbum({
					filePath: imgUrl,
					success: () => {
						that.posterBtnDisabled=false;
						uni.hideLoading();
						uni.showToast({
							title: '保存成功'
						});
					},
					fail: () => {
						that.posterBtnDisabled=false;
						uni.hideLoading();
						that.$util.toast('保存失败');
					}
				});
				// #endif
			},
			async onAppShare(type) {
				let that = this;
				if(this.posterBtnDisabled){
					return;
				}
				that.posterBtnDisabled=true;
				uni.showLoading({
					title: '图片获取中'
				});
				let imgUrl = "";
				let onlineUrl = "";
				if (that.promoteBgImgs[that.swiperIndex] && that.promoteBgImgs[that.swiperIndex].shareImg) {
					that.sharePoster(type, that.promoteBgImgs[that.swiperIndex].shareImg);
					return;
				} else {
					imgUrl = await that.posterImage;
				}

				var p = plus.io.convertLocalFileSystemURL(imgUrl);
				// 转换分享图片为file开头
				let url = 'file://' + p;

				uni.uploadFile({
					url: this.$util.interfaceUrl() + this.serverUrl,
					filePath: url,
					name: 'files',
					formData: {
						'bucketType': this.bucketType
					},
					header: {
						"Authorization": this.$util.getToken()
					},
					success: (res) => {
						if (res.statusCode == 200) {
							//返回结果 此处需要按接口实际返回进行修改
							let d = JSON.parse(res.data.replace(/\ufeff/g, "") || "{}")
							//判断code，以实际接口规范判断
							if (d.status === 0) {
								that.promoteBgImgs[that.swiperIndex].shareImg = d.data[0]; //存起来方便再次分享使用
								that.sharePoster(type, d.data[0]);
							}
							// resolve(index)
						} else {
							that.posterBtnDisabled=false;
							uni.hideLoading();
							uni.showToast({
								title: '分享图片出错，请稍后再试'
							});
						}
						
					},fail: (res) => {
						that.posterBtnDisabled=false;
						uni.hideLoading();
						console.log('生成异常', res)
					}
				})
			},
			sharePoster(type, url) {
				let that=this;
				uni.showLoading({
					title: '准备去分享'
				});
				// 最长4s自动关闭
				setTimeout(() => {
					uni.hideLoading();
					that.posterBtnDisabled=false;
				}, 4000);
				
				let scene = ''
				if (type == '1') { //分享好友
					scene = 'WXSceneSession'
				} else if (type == '2') { //分享朋友圈
					scene = 'WXSenceTimeline'
				}
				uni.share({
					provider: 'weixin',
					scene: scene,
					type: 2,
					imageUrl: url,
					success: function(res) {
						that.posterBtnDisabled=false;
						uni.hideLoading();
						uni.showToast({
							title: '分享成功'
						});
					},
					fail: function(err) {
						that.posterBtnDisabled=false;
						uni.hideLoading();
						uni.showToast({
							title: '分享失败'
						});
						console.log('fail:' + JSON.stringify(err));
					},
					complete:function(){
						that.posterBtnDisabled=false;
						uni.hideLoading();
					},

				});
			},
			// 海报计算实际显示x
			calculateX(value) {
				let windowWidth;
				uni.getSystemInfo({
					success(res) {
						windowWidth = res.windowWidth;
					}
				})
				console.log(windowWidth)
				const realVal = 750 / uni.upx2px(750) * (windowWidth * value / 375) + 'rpx';
				return realVal;
			},
			// 海报计算实际显示y
			calculateY(value, type) {
				let windowHeight;
				uni.getSystemInfo({
					success(res) {
						windowHeight = res.windowHeight
						// windowHeight = (667 * res.windowWidth) / 375;
					}
				})
				// 667 pX海报区域高度
				let realVal;
				if (type === 'y') {
					realVal = 750 / uni.upx2px(750) * (windowHeight * value / 725) + 'rpx';
				} else if (type === 'h') {
					realVal = 750 / uni.upx2px(750) * (windowHeight * value / 725) + 'rpx';
				}
				return realVal;
			},
			onUnload(){
				this.posterBtnDisabled=false;
				uni.hideLoading();
			}
		},
	};
</script>
<style lang="scss">
	.poster_page {
		width: 100%;
		height: 100vh;
		overflow: hidden;
		display: flex;
		align-items: center;
		// padding-bottom: constant(safe-area-inset-bottom);
		// padding-bottom: env(safe-area-inset-bottom);

		.poster_canvas {
			// width: 750rpx;
			// height: 1334rpx;
			position: fixed;
			top: -10000rpx;
			left: 0rpx;
		}

		.swiper-tall {
			width: 100%;
			display: flex;
			align-items: center;

			.swiper-container {
				display: flex;
				align-items: center;

				.swiper-item {
					height: 100%;
					width: 100%;
					// text-align: center;
					broder-radius: 6upx;
					background-color: #f5f5f5;
					// transform: scale(0.98, 0.9);
					box-shadow: 0 0 10rpx #ccc;
					position: relative;
					font-size: 28rpx;

					.swiper-mask {
						width: 100%;
						height: 100%;
						position: absolute;
						left: 0;
						top: 0;
						background: rgba(255, 255, 255, .3);
						z-index: 10;
						display: block;
						transition: 0.5s ease-in-out;
					}

					.poster-bg-image {
						width: 100%;
						height: 100%;
					}
					.poster-top-text{
						width: 600rpx;
						height:60rpx;
						line-height: 60rpx;
						border-radius: 30rpx;
						position: absolute;
						left:50%;
						margin-left:-300rpx;
						text-align: center;
						background-color: #db4e46;
						color: #fff;
						font-size: 30rpx;
						text-align: center;
						padding-left: 20rpx;
					}
					.poster-mid-text{
						width: 400rpx;
						position: absolute;
						left:50%;
						margin-left:-200rpx;
						text-align: center;
						font-size: 24rpx;
						.red{
							color: $red;
						}
					}
					.poster-code-image,
					.poster-avatar,
					.poster-username,
					.poster-num,
					.poster-btn {
						position: absolute;
					}

					.poster-code-image {
						position: absolute;
						width: 160rpx;
						height: 160rpx;
						// left: 50%;
						// bottom: 140rpx;
						// transform: translateX(-50%);
						font-size: 32rpx;
					}

					.poster-avatar {
						font-size: 36rpx;
					}

					.poster-username {
						width: 100%;
						left:0;
						text-align: center;
						.name {
							font-size: 30rpx;
						}
						.num {
							font-size: 26rpx;
							color: #999
						}

					}

					.poster-num {}

					.poster-btn {
						width: 500rpx;
						height: 88rpx;
						line-height: 88rpx;
						border-radius: 44rpx;
						background: linear-gradient(to top, #fdc34b 0%, #ffe7a4 100%) !important;
						color: #f15e18;
						font-size: 36rpx;

						&.disabled-btn {
							background: linear-gradient(to top, #fdc34b 0%, #ffe7a4 100%) !important;
							opacity: 0.8;
						}
					}

					&.active {
						// transform: scale(1);

						.swiper-mask {
							display: none;

						}
					}
				}
			}
		}



		.flex-column {
			width: 600rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			position: relative;

			.popup-close {
				position: absolute;
				width: 70rpx;
				height: 70rpx;
				right: 10rpx;
				top: 20rpx;
				color: #fff;
				font-size: 50rpx;
				padding: 10rpx;
				z-index:1000;
			}

			.img {
				width: 100%;

				.posterImage {
					width: 100%;
					display: block;
					margin: 0 auto;
				}
			}

			.flex-row {
				width: 100%;
				display: flex;
				flex-direction: row;
				justify-content: space-around;
				position: absolute;
				bottom: 30rpx;
				
				.btn {
					width: 160rpx;
					text-align: center;

					image {
						width: 80rpx;
						height: 80rpx;
						margin: 10rpx auto 0;
						border-radius: 40rpx;
						box-shadow: 0px 4rpx 24rpx 0px rgba(143, 97, 95, 0.1);
					}

					.icon-wrap {
						width: 80rpx;
						height: 80rpx;
						margin: 10rpx auto 0;
						border-radius: 40rpx;
						text-align: center;
						line-height: 82rpx;
						box-shadow: 0px 4rpx 24rpx 0px rgba(143, 97, 95, 0.1);
						position: relative;

						
						.bg {
							width: 60rpx;
							height: 60rpx;
							
							border-radius: 30rpx;
							background-color: #fff;
							position: absolute;
							left: 10rpx;
							top: 10rpx;
							z-index:1;
						}
						.iconfont{
							position: absolute;
							left: 0rpx;
							top: 0rpx;
							z-index:2;
						}
						.green {
							color: #66d020;
							font-size: 80rpx;
						}

						.yellow {
							color: #f3c332;
							font-size: 82rpx;
						}

					}
					.text {
						display: inline-block;
						color: #fff;
						font-size: 24rpx;
					}
					
				}
				&.disabled-style{
					opacity:0.7 ;
				}
			}

			.marginTop2vh {
				margin-top: 2vh;
			}
		}
	}
</style>
